from datetime import datetime
from sqlite3 import Date
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm.session import Session

from common.constants import KEYUSED_MAXTIMES
from .base import Base  # 从本地base.py导入Base

class UserKey(Base):
    __tablename__ = "user_key"

    id = Column(Integer, primary_key=True)
    key = Column(String, unique=True, index=True) # 唯一的key
    remainder = Column(Integer) # 剩余可使用次数

    @classmethod
    def create(cls, db: Session, key: str, remainder: int = KEYUSED_MAXTIMES) -> 'UserKey':
        user_key = UserKey(key=key, remainder=remainder)
        db.add(user_key)
        db.commit()
        return user_key

    def read(self, db: Session, key: str) -> 'UserKey':
        return db.query(UserKey).filter_by(key=key).first()

    def update(self, db: Session, key: str, remainder: int) -> 'UserKey':
        user_key = db.query(UserKey).filter_by(key=key).first()
        if user_key is None:
            return None
        user_key.remainder = remainder
        db.commit()
        db.refresh(user_key)
        return user_key

    def delete(self, db: Session, key: str) -> bool:
        user_key = db.query(UserKey).filter_by(key=key).first()
        if user_key is None:
            return False
        db.delete(user_key)
        db.commit()
        return True


class UsedLog(Base):
    __tablename__ = "used_log"

    id = Column(Integer, primary_key=True)
    key = Column(String, index=True) # 对应的key
    lastime = Column(DateTime) # 最后使用时间
    ip = Column(String) # 最后使用的ip
    useragent = Column(String) # 最后使用的useragent
    
    @classmethod
    def create(cls, db: Session, key: str, lastime: datetime, ip: str = None, useragent: str = None) -> 'UsedLog':
        """创建一条使用日志记录"""
        used_log = UsedLog(
            key=key,
            lastime=lastime,
            ip=ip,
            useragent=useragent
        )
        db.add(used_log)
        db.commit()
        return used_log

    def read(self, db: Session, key: str) -> 'UsedLog':
        """根据ID读取一条使用日志记录"""
        return db.query(UsedLog).filter_by(key=key).first()

    # 更新使用记录，如果不存在则创建
    def update(self, db: Session, key: str, lastime: datetime, ip: str = None, useragent: str = None) -> 'UsedLog':
        """更新一条使用日志记录"""
        used_log = db.query(UsedLog).filter_by(key=key).first()
        if used_log:
            used_log.lastime = lastime
            if ip is not None:
                used_log.ip = ip
            if useragent is not None:
                used_log.useragent = useragent
            db.commit()
            db.refresh(used_log)
        else:
            used_log = UsedLog.create(db, key, lastime, ip, useragent)
        return used_log

    def delete(self, db: Session, key: str) -> bool:
        """根据ID删除一条使用日志记录"""
        used_log = db.query(UsedLog).filter_by(key=key).first()
        if used_log:
            db.delete(used_log)
            db.commit()
            return True
        return False
